package com.sunny.ynhz.ui.patrol.problems.draft;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sunny.ynhz.R;
import com.sunny.ynhz.adapter.PatrolDraftAdapter;
import com.sunny.ynhz.api.ApiService;
import com.sunny.ynhz.api.upload.DefaultProgressListener;
import com.sunny.ynhz.api.upload.RetrofitUtil;
import com.sunny.ynhz.api.upload.UploadFileRequestBody;
import com.sunny.ynhz.bean.PathUploadBean;
import com.sunny.ynhz.bean.PatrolBean;
import com.sunny.ynhz.db.RealmUtils;
import com.sunny.ynhz.ui.base.BaseFragment;
import com.sunny.ynhz.utils.FileUtils;
import com.sunny.ynhz.utils.SPUtil;
import com.sunny.ynhz.utils.ShowUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by luao on 2017/7/24.
 */

public class PatrolDraftFragment extends BaseFragment {

    @BindView(R.id.problem_draft_recycle)
    RecyclerView problemDraftRecycle;
    private PatrolDraftAdapter mPatrolDraftAdapter;
    private Realm mRealm;
    private List<PatrolBean> patrolBeanList;
    private RealmResults<PatrolBean> patrolBeanRealmList;
    private RealmResults<PatrolBean> patrolBeanRealmListUserIdNull;
    private Handler mHandler = new Handler() {
        /**
         * what是文件上传百分比
         *
         * @param msg
         */
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    if (msg.what > 0) {

                    }
                    break;
            }
        }
    };

    private File tempfile;
    private String userId;

    public static PatrolDraftFragment getInstance() {
        return new PatrolDraftFragment();
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_problem_draft;
    }

    @Override
    protected void init() {
        super.init();
        mRealm = RealmUtils.getDeleteRealm();
        patrolBeanList = new ArrayList<>();
        userId = SPUtil.get("userId", "").toString();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
        problemDraftRecycle.setLayoutManager(linearLayoutManager);
        mPatrolDraftAdapter = new PatrolDraftAdapter(patrolBeanList);
        problemDraftRecycle.setAdapter(mPatrolDraftAdapter);
        problemDraftRecycle.setItemAnimator(new DefaultItemAnimator());
        patrolBeanRealmList = mRealm.where(PatrolBean.class).equalTo("isUploaded", false).equalTo("isEnd",true).equalTo("userId", userId).findAllAsync();
        patrolBeanRealmList.addChangeListener(new RealmChangeListener<RealmResults<PatrolBean>>() {
            @Override
            public void onChange(RealmResults<PatrolBean> patrolBeen) {
                if(patrolBeen!=null&&patrolBeen.size()>0){
                    patrolBeanList.clear();
                    patrolBeanList.addAll(patrolBeen);
                    mPatrolDraftAdapter.notifyDataSetChanged();
                }
                else {
                    patrolBeanRealmListUserIdNull = mRealm.where(PatrolBean.class).equalTo("isUploaded", false).equalTo("isEnd",true).findAllAsync();
                    patrolBeanRealmListUserIdNull.addChangeListener(new RealmChangeListener<RealmResults<PatrolBean>>() {
                        @Override
                        public void onChange(RealmResults<PatrolBean> patrolBeen) {
                            if(patrolBeen!=null&&patrolBeen.size()>0){
                                patrolBeanList.clear();
                                patrolBeanList.addAll(patrolBeen);
                                mPatrolDraftAdapter.notifyDataSetChanged();
                            }
                        }
                    });
                }

            }
        });

        mPatrolDraftAdapter.setOnBtnsClick(new PatrolDraftAdapter.OnClickListener() {
            @Override
            public void onItemClick(PatrolBean patrolBean, int position) {
                Intent intent = new Intent(activity, PatrolPathActivity.class);
                intent.putExtra("id", patrolBean.getId());
                startActivity(intent);
            }

            @Override
            public void onUploadPatrolBtnsClick(PatrolBean patrolBean, final int position) {
                tempfile = FileUtils.createTmpJsonFile(activity);
                Gson gson = new Gson();
                File jsonFile = FileUtils.getFileFromBytes(gson.toJson(mRealm.copyFromRealm(patrolBean.getLocationBeanlist())), tempfile.getPath());
                uploadPatrol(patrolBean.getId(), SPUtil.get("userId", "null").toString(), patrolBean.isOnline(),
                        patrolBean.getStartTime(), patrolBean.getEndTime(), null, null, patrolBean.getDistance() / 1000, true,
                        patrolBean.getStartLgtd(), patrolBean.getStartLttd(), patrolBean.getEndLgtd(), patrolBean.getEndLttd(), jsonFile);
                Log.e("hu",patrolBean.getRiverId()+"-----"+patrolBean.getSectionId());
                ApiService uploadFileService = RetrofitUtil.createService(ApiService.class);
                Map<String, RequestBody> requestBodyMap = new HashMap<>();
                UploadFileRequestBody fileRequestBody = new UploadFileRequestBody(jsonFile, new DefaultProgressListener(mHandler, 1));
                requestBodyMap.put("jsonfile\"; filename=\"" + jsonFile.getName(), fileRequestBody);
                uploadFileService.uploadPatrol(patrolBean.getId(), SPUtil.get("userId", "null").toString(), patrolBean.isOnline(),
                        patrolBean.getStartTime(), patrolBean.getEndTime(),patrolBean.getRiverId(), patrolBean.getSectionId(), patrolBean.getDistance() / 1000, true,
                        patrolBean.getStartLgtd(), patrolBean.getStartLttd(), patrolBean.getEndLgtd(), patrolBean.getEndLttd(), requestBodyMap).
                        subscribeOn(Schedulers.io()).
                        observeOn(AndroidSchedulers.mainThread()).
                        subscribe(new Subscriber<PathUploadBean>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                ShowUtils.inItPopwin(activity, "正在上传巡河信息");
                            }

                            @Override
                            public void onCompleted() {
                                ShowUtils.closePopwindow();
                            }

                            @Override
                            public void onError(Throwable e) {
                                Toast.makeText(activity, e.toString(), Toast.LENGTH_LONG).show();
                                ShowUtils.closePopwindow();

                            }

                            @Override
                            public void onNext(PathUploadBean s) {
                                Toast.makeText(activity, "轨迹上传成功", Toast.LENGTH_LONG).show();
                                mRealm.executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {
                                        patrolBeanRealmList.deleteFromRealm(position);
                                        patrolBeanList.remove(position);
                                        mPatrolDraftAdapter.notifyItemRemoved(position);
                                    }
                                });
                                if(tempfile.exists()){
                                    tempfile.delete();
                                }
                            }
                        });

            }

            @Override
            public void onDeletePatrolBtnsClick(PatrolBean patrolBean, final int position) {
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        patrolBeanRealmList.deleteFromRealm(position);
                        patrolBeanList.remove(position);
                        mPatrolDraftAdapter.notifyItemRemoved(position);
                    }
                });
            }


        });
    }

    /**
     * 结束巡河巡河上传（新的接口）
     *
     * @param patrolId  巡河场次id
     * @param userId    用户id
     * @param isOnLine  是否在线巡河
     * @param starttime 开时时间
     * @param endtime   结束时间
     * @param riverId   河涌id
     * @param sectionId 河段id
     * @param distance  巡河距离
     * @param isEnd     是否结束
     * @param startLgtd 巡河开始经度
     * @param startLttd 巡河开始纬度
     * @param endLgtd   巡河结束经度
     * @param endLttd   巡河结束纬度
     * @param file      路径json
     */
    public void uploadPatrol(String patrolId, String userId, boolean isOnLine, String starttime, String endtime, String riverId, String sectionId, Float distance, boolean isEnd, Double startLgtd, Double startLttd, Double endLgtd, Double endLttd, File file) {

    }

    @Override
    protected void setUpView() {
        super.setUpView();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }
}
